<?php

class User {

	public static function checkpsw($login) {
		if (isset($_SESSION['user'])) {
			$uid = $_SESSION['user']['uid'];
			$password = sha1($login['password']);
			$data = DB::query("SELECT password FROM user WHERE uid = '$uid'")->fetch_object();
			return $data->password == $password;
		} else {
			$username = DB::esc($login['login-name']);
			$password = sha1($login['login-psw']);
			$data = DB::query("SELECT password FROM user WHERE username = '$username'")->fetch_object();
			return $data->password == $password;
		}
	}

	// return 1 if no such value for the given field
	public static function checkfield($fields) {
		$field = DB::esc($fields['field']);
		$data = DB::esc($fields['data']);

		if (DB::hasData("SELECT * FROM user WHERE $field = '$data'")) {
			return 0;
		} else {
			return 1;
		}
	}

	public static function login($login) {
		$username = DB::esc($login['login-name']);
		$password = sha1($login['login-psw']);
		$data = DB::query("SELECT * FROM user WHERE username = '$username'")->fetch_object();
		if ($data->password == $password) {
			$uid = $data->uid;
			if (!DB::query("INSERT INTO online_user (uid) VALUES ('$uid')")) {
				DB::query("UPDATE online_user SET counter = counter + 1 WHERE uid = '$uid'");
			}
			unset($_SESSION['user']);
			$_SESSION['user']['uid'] = $uid;
			User::update_user_session();
			return 1;
		} else {
			return 0;
		}
	}

	public static function update_online_ts() {
		$uid = $_SESSION['user']['uid'];
		if (User::is_online($uid)) {
			return DB::query("UPDATE online_user SET ts = CURRENT_TIMESTAMP WHERE uid = '$uid'");
		} else {
			return DB::query("INSERT INTO online_user (uid) VALUES ('$uid')");
		}
	}

	public static function is_online($uid) {
		return DB::hasData("SELECT * FROM online_user WHERE uid = '$uid'");
	}

	public static function logout() {
		$uid = $_SESSION['user']['uid'];
		unset($_SESSION['user']);
		$counter = DB::query("SELECT counter FROM online_user WHERE uid = '$uid'");
		$counter = $counter->fetch_object()->counter;
		if ($counter == 1) {
			return DB::query("DELETE FROM online_user WHERE uid = '$uid'");
		} else {
			return DB::query("UPDATE online_user SET counter = counter - 1 WHERE uid = '$uid'");
		}
	}

	public static function all_users() {
		$result = DB::query("SELECT * FROM user");
		$users = array();
		while ($user = $result->fetch_object()) {
			$users[] = $user;
		}
		return $users;
	}

	public static function all_online_users() {
		$result = DB::query("SELECT username, uid, avatar, online_user.ts, online_user.ts AS ts FROM online_user JOIN user USING(uid)");
		$users = array();
		while ($user = $result->fetch_object()) {
			$users[] = $user;
		}
		return $users;
	}

	public static function register($regfields) {
		$invite = DB::esc($regfields['reg_invite']);
		$email = DB::esc($regfields['reg_email']);
		$username = DB::esc($regfields['reg_username']);
		$password = sha1($regfields['reg_password']);

		if (!DB::hasData("SELECT * FROM invite_code WHERE code = '$invite'")) {
			return -2; // invalid invite code
		}

		if (DB::hasData("SELECT * FROM user WHERE username = '$username' OR email = '$email'")) {
			return -1; // username/email is already registered
		} else {
			$query = "INSERT INTO user (
				email,
				username,
				password
				)
				VALUES (
				'$email',
				'$username',
				'$password'
				)";
			if (DB::query($query)) {
				DB::query("DELETE FROM invite_code WHERE code = '$invite'");
				$ts = DB::query("SELECT ts FROM user WHERE username = '$username'")->fetch_object()->ts;
				DB::query("UPDATE user SET join_ts = '$ts' WHERE username = '$username'");
				return 1;
			} else {
				return 0; //something is wrong
			}
		}
	}

	public static function activate($uid, $code) {
		// not yet implemented
	}

	public static function generateInvite($from, $num) {
		if ($_SESSION['user']['username'] != 'admin') {
			return 0; // only admin user could do this
		}
		for ($i = $from; $i < $from + $num; $i++) {
			DB::query("INSERT INTO invite_code (code) VALUES ('" . md5($i . "wormhole for the win!!") . "')");
		}
		return 1;
	}

	public static function getInvites() {
		if ($_SESSION['user']['username'] != 'admin') {
			return 0; // only admin user could do this
		}
		$result = DB::query("SELECT * FROM invite_code");
		echo "<h4>Total available codes: " . $result->num_rows . "</h4>";
		while ($code = $result->fetch_object()) {
			echo "<p style='font-family:monospace;'>" . $code->code . "</p>";
		}
		return 1;
	}

	public static function circle($uid_to, $nid) {
		$nid = (int) $nid;
		$uid_to = (int) $uid_to;
		$uid_from = $_SESSION['user']['uid'];
		if (DB::query("INSERT INTO circle ( uid_from, uid_to, nid ) VALUES ( '$uid_from', '$uid_to', '$nid' ) ")) {
			return 1;
		} else {
			return 0;
		}
	}

	public static function uncircle($uid_to, $nid) {
		$uid_to = (int) $uid_to;
		$uid_from = $_SESSION['user']['uid'];
		return DB::query("DELETE FROM circle WHERE uid_from = '$uid_from' AND uid_to = '$uid_to' AND nid = '$nid' ");
	}

    public static function uncircle_all_nebulas($uid_to){
        $uid_to = (int) $uid_to;
		$uid_from = $_SESSION['user']['uid'];
		return DB::query("DELETE FROM circle WHERE uid_from = '$uid_from' AND uid_to = '$uid_to'");
    }

	public static function getCircles($uid) {
		$uid = (int) $uid;
		$result = DB::query("SELECT uid_to, nid, name, username, avatar 
							FROM circle 
							JOIN user ON circle.uid_to = user.uid 
							JOIN nebula
							USING( nid ) 
							WHERE uid_from = '$uid'");
		$users = array();
		while ($user = $result->fetch_object()) {
			$users[] = $user;
		}
		return $users;
	}

	public static function getUser($uid) {
		$uid = (int) $uid;
        $uid_from = $_SESSION['user']['uid'];
		$result = DB::query("SELECT user.uid AS uid, username, avatar, fullname, email, blog, birthday, description, gender,
							 circle.fid IS NOT NULL AS circled
                             from user
                             LEFT JOIN circle on circle.uid_from='$uid_from' AND circle.uid_to=user.uid
                             WHERE user.uid = '$uid'");
		$users = array();
		while ($user = $result->fetch_object()) {
			$users[] = $user;
		}
		return $users;
	}
	
	public static function getSelfInfo() {
		$uid = $_SESSION['user']['uid'];
		$result = DB::query("SELECT * FROM user WHERE user.uid = '$uid'");
		$users = array();
		while ($user = $result->fetch_object()) {
			$users[] = $user;
		}
		return $users;
	}

	public static function updatefield($post) {
		if (!isset($_SESSION['user']))
			return -1;
		$field = DB::esc($post['field']);
		$newval = DB::esc($post['newval']);
		$uid = $_SESSION['user']['uid'];
		$query;
		if ($field == 'password') {
			$oldpsw = sha1($post['password']);
			$newval = sha1($newval);
			if (!User::checkpsw($post)) {
				return 0;
			}
			$query = "UPDATE user SET $field = '$newval' WHERE uid = '$uid' AND password = '$oldpsw'";
		} else {
			$query = "UPDATE user SET $field = '$newval' WHERE uid = '$uid'";
		}
		$res = DB::query($query);
		if ($res) {
			$_SESSION['user'][$field] = $newval;
			return 1;
		} else {
			return 0;
		}
	}

	public static function update_settings($info) {
		if (!isset($_SESSION['user']))
			return -1;
		$uid = $_SESSION['user']['uid'];
		$query = "UPDATE user SET";
		if (isset($info['fullname'])) {
			$fullname = $info['fullname'];
			$query .= " fullname = '$fullname'";
		}
		if (isset($info['avatar'])) {
			$avatar = $info['avatar'];
			$query .= ", avatar = '$avatar'";
		}
		if (isset($info['gender'])) {
			$gender = $info['gender'];
			$query .= ", gender = '$gender'";
		}
		if (isset($info['description'])) {
			$description = $info['description'];
			$query .= ", description = '$description'";
		}
		if (isset($info['blog'])) {
			$blog = $info['blog'];
			$query .= ", blog = '$blog'";
		}
		if (isset($info['email'])) {
			$email = $info['email'];
			$query .= ", email = '$email'";
		}
		if (isset($info['birthday'])) {
			$birthday = $info['birthday'];
			$query .= ", birthday = '$birthday'";
		}
		if ($query == "UPDATE user SET") {
			return -1; // no valid fileds to be updated
		} else {
			$query .= " WHERE uid = '$uid'";
			User::update_user_session();
			return DB::query($query);
		}
	}

	public static function update_user_session() {
		$uid = $_SESSION['user']['uid'];
		$data = DB::query("SELECT * FROM user WHERE uid = '$uid'")->fetch_object();
		$_SESSION['user']['fullname'] = $data->fullname;
		$_SESSION['user']['email'] = $data->email;

		$_SESSION['user']['username'] = $data->username;
		$_SESSION['user']['avatar'] = $data->avatar;
		$_SESSION['user']['gender'] = $data->gender;
		$_SESSION['user']['group'] = $data->group;
		$_SESSION['user']['birthday'] = $data->birthday;
		$_SESSION['user']['blog'] = $data->blog;
		$_SESSION['user']['description'] = $data->description;
		return 1;
	}

}

?>
